package com.sun.dubbo.webmanage.service.impl;

import java.lang.reflect.InvocationTargetException;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.beanutils.BeanUtils;

import com.sun.commons.pojo.TbItemCatCustom;
import com.sun.dubbo.webmanage.service.TbItemCatDubboService;
import com.sun.webmanage.mapper.TbItemCatMapper;
import com.sun.webmanage.model.TbItemCat;
import com.sun.webmanage.model.TbItemCatExample;
import com.sun.webmanage.model.TbItemCatExample.Criteria;

public class TbItemCatDubboServiceImpl implements TbItemCatDubboService{

	@Resource
	private TbItemCatMapper tbItemCatMapper;
	
	@Override
	public List<TbItemCat> listTbItemCatByPid(long pid) {
		TbItemCatExample example = new TbItemCatExample();
		example.createCriteria().andParentIdEqualTo(pid).andStatusEqualTo(1);
		List<TbItemCat> listdata = tbItemCatMapper.selectByExample(example);
		return listdata;
	}

	@Override
	public TbItemCat loadTbItemCatByPK(long id) {
		return tbItemCatMapper.selectByPrimaryKey(id);
	}

	@Override
	public TbItemCatCustom linkCat(TbItemCatCustom leaf) {
		TbItemCat parent = tbItemCatMapper.selectByPrimaryKey(leaf.getParentId());
		TbItemCatCustom parentCus = new TbItemCatCustom();
		TbItemCatCustom root = null;
		TbItemCatCustom retCat = null;
		if(parent!=null){
			try {
				BeanUtils.copyProperties(parentCus, parent, true);
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				e.printStackTrace();
			}
			root = linkCat(parentCus);
			retCat = root;
			//root.getChild....setChild
			for(int i=0;i<root.getDepth();i++){
				root = root.getChild();
			}
			root.setChild(leaf);
			root.setDepth(root.getDepth()+1);
		}else{
			leaf.setDepth(0);
			return leaf;
		}
		
		return retCat;
	}

	@Override
	public boolean upadteTbItemCat(TbItemCat tbItemCat) {
		if(tbItemCatMapper.updateByPrimaryKeySelective(tbItemCat)>0){
			return true;
		}
		return false;
	}

}
